#!/bin/bash

# 回收站功能脚本
TRASH_DIR="$HOME/.trash"
TRASH_LOG="$HOME/.trash.log"
VERSION="1.1"

if [ ! -d "$TRASH_DIR" ]; then
	mkdir -p "$TRASH_DIR"
	touch "$TRASH_LOG"
	chmod 600 "$TRASH_LOG"
fi

# 显示帮助信息
show_help() {
    echo "Usage: trash [OPTION]... [FILE]..."
    echo "Move files/folders to trash instead of permanently deleting them."
    echo ""
    echo "Options:"
	echo "  -h, --help    show this help message and exit"
	echo "  -e, --empty   empty trash"
    echo "  -l, --list    list trash content"
    echo "  -s, --stats   show trash stats"
    echo "  -v, --version show trash version"
	echo "  -r, --restore restore files from trash"
    echo ""
    echo "Without options, moves specified files to trash."
    echo ""
    echo "auto clean up files thast have exitsted in ~/.trash/ directory more then 30 days file , when using the trash command delete to file"
}

# 显示版本信息
show_version() {
	echo "trash v$VERSION"
	echo "Linux trash"
}

# 列出回收站内容
list_trash() {
    if [ ! -d "$TRASH_DIR" ] || [ -z "$(ls -A "$TRASH_DIR")" ]; then
        echo "trash is empty!"
        return
    fi
    
    echo "TRASH_DIR (~/.trash/):"
    echo "――――――――――――――――――――――――――――――――――――――"
    find "$TRASH_DIR" -type f -printf "%f\t%TY-%Tm-%Td %TH:%TM\t%s bytes\n" | column -t -s $'\t'
    echo "――――――――――――――――――――――――――――――――――――――"
}

# 清空回收站
empty_trash() {
    if [ ! -d "$TRASH_DIR" ]; then
        echo "trash is empty!"
        return
    fi
    
    read -p "please confirm to empty trash? (y/n): " confirm
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        rm -rf "${TRASH_DIR:?}/"*
        echo "trash was emptied!"
    else
        echo "opreation canceled!"
    fi
}

# 显示回收站统计信息
show_stats() {
    if [ ! -d "$TRASH_DIR" ]; then
        echo "trash is empty!"
        return
    fi
    
    file_count=$(find "$TRASH_DIR" -type f | wc -l)
    total_size=$(du -sh "$TRASH_DIR" | cut -f1)
    
    echo "trash_stats:"
    echo "file_count: $file_count"
    echo "tital_size: $total_size"
}

# 处理文件移动到回收站
move_to_trash() {
    # 确保回收站目录存在
    if [ ! -d "$TRASH_DIR" ]; then
        mkdir -p "$TRASH_DIR"
		touch "$TRASH_LOG"
		chmod 600 "$TRASH_LOG"
    fi
    
    # 检查是否提供了文件参数
    if [ $# -eq 0 ]; then
        echo "error: no files provided"
        echo "please make 'trash --help' for more information"
        exit 1
    fi
 
	echo "auto clean more then 30 days file..."
	find "$TRASH_DIR" -type f -mtime +30 -print | while read -r old_file; do
		filename=$(basename "$old_file")
		echo "delete more then 30 days file $filename"
		sed -i "/$filename/d" "$TRASH_LOG"
		rm -rf "$old_file"
	done

    moved_count=0
    for file in "$@"; do
        if [ ! -e "$file" ]; then
            echo "warning: '$file' does not exist"
            continue
        fi
        
		local original_file_path
		if [[ "$file" == /* ]]; then
			original_file_path="$file"
		else
			original_file_path="$PWD/$file"
		fi
        # 获取文件名和时间戳
        filename=$(basename "$file")
        timestamp=$(date +%Y%m%d_%H_%M_%S)
        new_name="${filename}.${timestamp}"
        
        # 移动到回收站
        if mv "$file" "$TRASH_DIR/$new_name"; then 
			echo "${new_name}|${original_file_path}|$(date +%Y-%m-%d\ %H:%M:%S)" >> "$TRASH_LOG"
			echo "trash: '$file' -> '$TRASH_DIR/$new_name'"
			moved_count=$((moved_count + 1))
		else
			echo "error: failed to move '$file' to '$TRASH_DIR/$new_name'"
		fi
    done
    
    echo "total $moved_count files moved to trash"
}

restore_file() {
	# 检查是否提供了文件参数
	if [ $# -eq 0 ]; then
		echo "error: no files provided"
		echo "please make 'trash --help' for more information"
		exit 1
	fi

	local file_in_trash="$1"
	local trash_file_path="${TRASH_DIR}/${file_in_trash}"
	if [ ! -e "${trash_file_path}" ]; then
		echo "error: '${trash_file_path}' does not exist"
		echo "please make 'trash --list' for more information"
		exit 1
	fi

	local original_file_path=$(grep "^${file_in_trash}|" "$TRASH_LOG" | head -n 1 | cut -d '|' -f 2)
	if [ -z "$original_file_path" ]; then
		echo "error: '${file_in_trash}' not found in trash log"
		echo "this file may have been deleted or moved manually"
		exit 1
	fi

	local original_dir=$(dirname "$original_file_path")
	if [ ! -d "$original_dir" ]; then
		mkdir -p "$original_dir"
		if [ $? -ne 0 ]; then
			echo "error: failed to create directory '$original_dir'"
			exit 1
		fi
	fi

	if [ -e "$original_file_path" ]; then
		echo "error: '$original_file_path' already exists"
		read -p "overwrite? (y/n): " -n 1 -r
		echo
		if [[ ! $REPLY =~ ^[Yy]$ ]]; then
			echo "operation canceled"
			exit 0
		fi
		rm -rf "$original_file_path"
	fi
	if mv -i "$trash_file_path" "$original_file_path"; then
		grep -v "^${file_in_trash}|" "$TRASH_LOG" > "$TRASH_LOG.tmp" && mv "$TRASH_LOG.tmp" "$TRASH_LOG"
		echo "restored '$file_in_trash' to '$original_file_path'"
	else
		echo "error: failed to restore '$file_in_trash'"
		exit 1
	fi
}
# 解析命令行参数
case "$1" in
    -h|--help)
        show_help
        ;;
    -e|--empty)
        empty_trash
        ;;
    -l|--list)
        list_trash
        ;;
    -s|--stats)
        show_stats
        ;;
    -r|--restore)
        shift
		restore_file "$@"
        ;;
    -v|--version)
        show_version
        ;;
    *)
        # 如果没有选项或选项不被识别，执行默认的移动操作
        if [[ "$1" == -* ]]; then
            echo "error: unknown option '$1'"
            echo "please make 'trash --help' for more information"
            exit 1
        else
            move_to_trash "$@"
        fi
        ;;

esac
